package com.jz.community.moduleshopping.address.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.bean.BaseCommLocateInfo;
import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.loaction.LocationActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.CommUtils;
import com.jz.community.basecomm.utils.ConverterUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.moduleshopping.address.smarttop.bean.City;
import com.jz.community.moduleshopping.address.smarttop.bean.County;
import com.jz.community.moduleshopping.address.smarttop.bean.Province;
import com.jz.community.moduleshopping.address.smarttop.bean.Street;
import com.jz.community.moduleshopping.address.smarttop.widget.AddressSelector;
import com.jz.community.moduleshopping.address.smarttop.widget.BottomDialog;
import com.jz.community.moduleshopping.address.smarttop.widget.OnAddressSelectedListener;
import com.jz.community.moduleshopping.R;
import com.jz.community.moduleshopping.R2;
import com.jz.community.moduleshopping.address.bean.AdCodeInfo;
import com.jz.community.moduleshopping.address.bean.BaseAddressInfo;
import com.jz.community.moduleshopping.address.task.AddAddressTask;
import com.jz.community.moduleshopping.address.task.GetAdCodeTask;
import com.jz.community.moduleshopping.address.task.UpdateAddressTask;

import butterknife.BindView;

/**
 * Created by Tony.Fan on 2018/5/3 09:37
 * <p>
 * 添加收货地址
 */
public class AddAddressActivity extends BaseMvpActivity implements OnAddressSelectedListener, AddressSelector.OnDialogCloseListener, AddressSelector.onSelectorAreaPositionListener {

    private static final int CODE_COMMUNITY = 0X00001;

    @BindView(R2.id.tv_back)
    ImageView tvBack;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.commit_order_toolbar)
    Toolbar commitOrderToolbar;
    @BindView(R2.id.et_belong_address)
    TextView etBelongAddress;
    @BindView(R2.id.et_belong_address_detail)
    EditText etBelongAddressDetail;
    @BindView(R2.id.et_goods_receipt_name)
    EditText etGoodsReceiptName;
    @BindView(R2.id.et_goods_receipt_phone)
    EditText etGoodsReceiptPhone;
    @BindView(R2.id.cb_isDefault_address)
    CheckBox cbIsDefaultAddress;
    @BindView(R2.id.button_commit_address)
    Button buttonCommitAddress;
    @BindView(R2.id.iv_clean_message1)
    ImageView ivCleanMessage1;
    @BindView(R2.id.iv_clean_message)
    ImageView ivCleanMessage;
    @BindView(R2.id.ll_location_address)
    RelativeLayout llLocationAddress;
    @BindView(R2.id.location_iv)
    ImageView locationIv;
    private BottomDialog dialog;
    private String isDefault = "0";
    private Bundle bundle;
    private SearchAddressControl searchAddressControl;
    private String id;
    private String provinceCode;
    private String cityCode;
    private String areaCode;
    private String townCode;

    @Override
    protected void initDatas() {
        bundle = getIntent().getExtras();
        if (!Preconditions.isNullOrEmpty(bundle)) {
            id = bundle.getString("id");
            etGoodsReceiptName.setText(bundle.getString("name"));
            etGoodsReceiptPhone.setText(bundle.getString("phone"));
            updateReceivingAddress();
            cbIsDefaultAddress.setChecked(false);
            isDefault = "-1";
        } else {
            LoginBaseInfo loginBaseInfo = BaseSpUtils.getInstance().getUserBaseInfo(this);
            if (!Preconditions.isNullOrEmpty(loginBaseInfo)) {
                etGoodsReceiptName.setText(loginBaseInfo.getName());
                etGoodsReceiptPhone.setText(loginBaseInfo.getMobi());
            }
        }
        initSearchControl();
    }

    private void initSearchControl() {
        searchAddressControl = new SearchAddressControl(this);
        searchAddressControl.showUI();
    }

    /**
     * 更新收货地址
     */
    private void updateReceivingAddress() {
        String address = bundle.getString("address");
        String addressDetails = bundle.getString("addressDetails");
        etBelongAddress.setText(address);
        etBelongAddressDetail.setText(addressDetails);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_shopping_activity_add_goods_receipt;
    }

    @Override
    protected void initView() {
        tvTitle.setText("收货地址");
        setImmersionBar(commitOrderToolbar);
    }

    @Override
    protected void addListener() {
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cbIsDefaultAddress.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isDefault = "0";
                } else {
                    isDefault = "-1";
                }
            }
        });

        locationIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toCommunity = new Intent(AddAddressActivity.this, LocationActivity.class);
                startActivityForResult(toCommunity, CODE_COMMUNITY);
            }
        });

        ivCleanMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etGoodsReceiptPhone.setText("");
            }
        });

        ivCleanMessage1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etGoodsReceiptName.setText("");
            }
        });

        buttonCommitAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName = etGoodsReceiptName.getEditableText().toString().trim();
                String userTel = etGoodsReceiptPhone.getEditableText().toString().trim();
                String address = etBelongAddress.getText().toString().trim();
                String addressDetail = etBelongAddressDetail.getText().toString().trim();
                if (isHasEmptyData(userName, userTel, address, addressDetail)) {
                    CommUtils.hideKeyboard(v, AddAddressActivity.this);
                    if (!Preconditions.isNullOrEmpty(bundle)) {
                        updateUserAddress(userName, userTel, address, addressDetail, provinceCode, cityCode, areaCode, townCode);
                    } else {
                        addUserAddress(userName, userTel, address, addressDetail, provinceCode, cityCode, areaCode, townCode);
                    }
                }
            }
        });

        etBelongAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRegionAddressDialog();
            }
        });
    }

    /**
     * 更新收货地址
     *
     * @param userName
     * @param userTel
     * @param address
     */
    private void updateUserAddress(String userName, String userTel, String address, String addressDetails, String provinceCode, String cityCode, String areaCode, String townCode) {
        new UpdateAddressTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                BaseAddressInfo userAddressInfo = (BaseAddressInfo) o;
                if (!Preconditions.isNullOrEmpty(userAddressInfo) && !Preconditions.isNullOrEmpty(userAddressInfo.getAddress())) {
                    saveUserMsg(address, addressDetails, userName, userTel,cityCode);
                    WpToast.l(AddAddressActivity.this, "更新成功");
                    finish();
                } else {
                    if (!Preconditions.isNullOrEmpty(userAddressInfo)) {
                        WpToast.l(AddAddressActivity.this, userAddressInfo.getMessage());
                    }
                }
            }
        }).execute(address, isDefault, userName, userTel, ConverterUtils.toString(id), addressDetails, provinceCode, cityCode, areaCode, townCode);
    }

    /**
     * 添加收货地址
     *
     * @param userName
     * @param userTel
     * @param address
     */
    private void addUserAddress(String userName, String userTel, String address, String addressDetails, String provinceCode, String cityCode, String areaCode, String townCode) {
        new AddAddressTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                BaseAddressInfo userAddressInfo = (BaseAddressInfo) o;
                if (!Preconditions.isNullOrEmpty(userAddressInfo) && !Preconditions.isNullOrEmpty(userAddressInfo.getAddress())) {
                    saveUserMsg(address, addressDetails, userName, userTel,cityCode);
                    WpToast.l(AddAddressActivity.this, "添加成功");
                    finish();
                } else {
                    if (!Preconditions.isNullOrEmpty(userAddressInfo)) {
                        WpToast.l(AddAddressActivity.this, userAddressInfo.getMessage());
                    }
                }
            }
        }).execute(address, isDefault, userName, userTel, addressDetails, provinceCode, cityCode, areaCode, townCode);
    }

    /**
     * 保存用户信息
     *
     * @param userName
     * @param userTel
     */
    private void saveUserMsg(String address, String addressDetail, String userName, String userTel,String cityCode) {
        Intent intent = new Intent();
        intent.putExtra("address", address + addressDetail);
        intent.putExtra("mentionName", userName);
        intent.putExtra("cityCode", cityCode);
        intent.putExtra("tel", userTel);
        intent.putExtra("isSelf", true);
        setResult(RESULT_OK, intent);
    }

    /**
     * 收货地址
     *
     * @param name
     * @param tel
     * @param address
     * @param addressDetail
     * @return
     */
    private boolean isHasEmptyData(String name, String tel, String address, String addressDetail) {
        if (Preconditions.isNullOrEmpty(name)) {
            WpToast.l(this, getString(R.string.name_cannot_be_empty));
            return false;
        }
        if (Preconditions.isNullOrEmpty(tel)) {
            WpToast.l(this, "手机号码不能为空");
            return false;
        }
        if (!CommUtils.isPhone(tel)) {
            WpToast.l(this, getString(R.string.set_valid_tel));
            return false;
        }
        if (Preconditions.isNullOrEmpty(address)) {
            WpToast.l(this, getString(R.string.fill_in_detailed_address));
            return false;
        }
        if (Preconditions.isNullOrEmpty(addressDetail)) {
            WpToast.l(this, getString(R.string.fill_in_detailed_address));
            return false;
        }
        return true;
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    /**
     * 显示地区弹框
     */
    private void showRegionAddressDialog() {
        dialog = new BottomDialog(this);
        dialog.setOnAddressSelectedListener(this);
        dialog.setDialogDismisListener(this);
        dialog.setTextSize(14);//设置字体的大小
        dialog.setIndicatorBackgroundColor(R.color.red);//设置指示器的颜色
        dialog.setTextSelectedColor(R.color.red);//设置字体获得焦点的颜色
        dialog.setTextUnSelectedColor(R.color.red);//设置字体没有获得焦点的颜色
        dialog.setSelectorAreaPositionListener(this);
        dialog.show();
    }

    @Override
    public void dialogclose() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @Override
    public void selectorAreaPosition(int provincePosition, int cityPosition, int countyPosition, int streetPosition) {

    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        provinceCode = (Preconditions.isNullOrEmpty(province) ? "" : province.id);
        cityCode = (Preconditions.isNullOrEmpty(city) ? "" : city.id);
        areaCode = (Preconditions.isNullOrEmpty(county) ? "" : county.id);
        townCode = (Preconditions.isNullOrEmpty(street) ? "" : street.id);
        String address = (Preconditions.isNullOrEmpty(province) ? "" : province.name) + (Preconditions.isNullOrEmpty(city) ? "" : city.name) + (Preconditions.isNullOrEmpty(county) ? "" : county.name) + (Preconditions.isNullOrEmpty(street) ? "" : street.name);
        getAdodeData(address, city.name);
        etBelongAddress.setText(address);
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 根据位置获取地理编码
     *
     * @param address
     * @param cityName
     */
    private void getAdodeData(String address, String cityName) {
        new GetAdCodeTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {
                AdCodeInfo adCodeInfo = (AdCodeInfo) o;
                if (!Preconditions.isNullOrEmpty(adCodeInfo) && !Preconditions.isNullOrEmpty(adCodeInfo.getGeocodes())) {
                    searchAddressControl.setCityCode(adCodeInfo.getGeocodes().get(0).getAdcode());
                    String location = adCodeInfo.getGeocodes().get(0).getLocation();
                    String[] locStr = location.split(",");
                    saveLocationMsg(locStr[0], locStr[1]);
                }
            }
        }).execute(address, cityName);
    }

    /**
     * 保存定位经纬度信息
     *
     * @param longitude
     * @param latitude
     */
    private void saveLocationMsg(String longitude, String latitude) {
        BaseCommLocateInfo locateInfo = new BaseCommLocateInfo();
        locateInfo.lon = longitude;
        locateInfo.lat = latitude;
        BaseSpUtils.getInstance().setCurrentCommuity(this, locateInfo);
    }

}
